var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate ,colorpicker = layui.colorpicker;

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
let operationList=[];
let salesmanList=[];
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList=getxmselect("#operationCode","operationCode", userTree);
        salesmanList=getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        salesmanList=getxmselect("#salesmanCode","salesmanCode", []);
    }
})()

form.render();//表单刷新
layer.ready(function () {
});
table.render({
    elem: '#maininformation'
    ,url:'drawback/findDrawbackListByPage'
    ,where:{operationCode : user.code, salesmanCode : user.code}
    ,toolbar: '#maininformationtoolbar'
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true, totalRowText: '合计'}
        ,{field:'drawbackCode', title:'退税编号',sort:true,width: 120,event: "moaiserialnumber"}
        ,{field:'shippingDate', title:'出运日期',sort:true,width: 120}
        ,{field:'customerName', title:'客户名称',sort:true,width: 120}
        ,{field:'registerDate', title:'登记日期',sort:true,width: 120}
        ,{field:'invoiceCode', title:'报关发票号',sort:true,width: 120}
        ,{field:'currencyName', title:'币种',sort:true,width: 120}
        ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
        ,{field:'declarationAmount', title:'报关金额',sort:true,width: 120, totalRow: true}
        ,{field:'theoreticalTaxRefund', title:'理论退税金额',sort:true,width: 120, totalRow: true}
        ,{field:'actualTaxRefund', title:'实际退税金额',sort:true,width: 120, totalRow: true}
        ,{field:'contractCode', title:'销售合同号',sort:true,width: 120}
        ,{field:'remarks', title:'备注',sort:true,width: 120}
        ,{field:'drawbackOperatorName', title:'退税人',sort:true,width: 120}
        ,{field:'exporterName', title:'出口单位',sort:true,width: 120}
        ,{field:'operatorName', title:'操作员',sort:true,width: 120}
        ,{field:'drawbackStatus', title:'单据类型',sort:true,width: 120,templet: function (d) {
                if (d.drawbackStatus==3){
                    return '登记箱';
                }else if (d.drawbackStatus==4){
                    return "完成箱";
                }
            }}
        ,{fixed: 'right', width:200, toolbar: '#maininformationeditor', title:'操作'}
    ]]
    ,id: 'maininformationtableid'
    ,height: $(document).height() - $('#maininformation').offset().top - 50
    ,page: true,
    //parseData：将返回的数据解析成table组件定义的格式
    parseData: function(res){//返回的数据
        return {
            "code": res.status,//解析接口的状态
            "count": res.total,//解析数据的长度
            "data": res.data//解析数据
        };
    }
    ,done(res, curr, count){
        lay('.colorvalue').each(function(){
            var xb = $(this).attr("data-id");
            var colors = "";
            for(var i = 0;i<res.data.length;i++){
                if(res.data[i].drawbackId == xb && typeof (res.data[i].markColor)!= "undefined" && res.data[i].markColor!=""){
                    Layui_SetDataTableRowColor('tablediv', $(this).attr("data-index"),res.data[i].markColor);
                    colors = res.data[i].markColor;
                }
            }
            colorpicker.render({
                elem: this //绑定元素
                , color: colors //设置默认色
                , done: function (color) {//点击颜色选择器的“确认”和“清除”按钮，均会触发 done 回调，回调返回当前选择的色值
                    let index = $(this.elem).attr("data-index");
                    Layui_SetDataTableRowColor('tablediv', index, color);
                    //保存修改的颜色
                    let drawbackId = res.data[index].drawbackId;
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        data: {"drawbackId":drawbackId,"color":color},
                        url: "drawback/updateMarkColor",
                        success: function (data) {
                            if (data.status == 200) {
                                layer.msg('修改成功');
                                table.reload("maininformationtableid");
                            } else {
                                layer.msg(data.msg);
                            }
                        }
                    });
                }

            });
        });
    }
});
//设置layui datatable的某一行的颜色
//DivId:datatable父div的 id;RowIndex:行序列号；Color：颜色字符串，如'#FF3030'
function Layui_SetDataTableRowColor(DivId, RowIndex, Color) {
    try {
        var div = document.getElementById(DivId);
        if (div != null){ //找到对象了
            var table_main = div.getElementsByClassName('layui-table-main');   //通过class获取table_main
            if (table_main != null && table_main.length > 0) {
                var table = table_main[0].getElementsByClassName('layui-table');   //通过class获取table
                if (table != null && table.length > 0) {
                    var trs = table[0].querySelectorAll("tr");
                    if (trs != null && trs.length > 0) {
                        trs[RowIndex].style.backgroundColor = Color;//背景颜色
                    }
                }
            }

        }
    } catch (e) {
        console.log(e.message);
    }
}
table.on('tool(maininformationtable)', function(obj){
    var data = obj.data;
    let drawbackId=data.drawbackId;
    if(obj.event === 'new') {
        parent.intab("views/jsp/Money/tpl/newtaxrebates.jsp?drawbackId="+obj.data.drawbackId,"登记退税")
    }else if(obj.event === 'complete'){
        layer.confirm('确定登记完成吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                data: {"drawbackId":drawbackId,"drawbackStatus":4},
                async:false,
                url:"drawback/updateDrawbackStatus",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('确认登记');
                    }else {
                        layer.msg('登记失败');
                    }
                }
            });
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定退回吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                data: {"drawbackId":drawbackId,"drawbackStatus":3},
                async:false,
                url:"drawback/updateDrawbackStatus",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('确认退回');
                    }else {
                        layer.msg('退回失败');
                    }
                }
            });
        });
    }else if (obj.event === "moaiserialnumber"){
        parent.intab("views/jsp/Money/tpl/viewtaxrebates.jsp?drawbackId="+obj.data.drawbackId,"退税明细")
    }
});

form.on('submit(submitform)', function(data){
    table.reload('maininformationtableid', {
        url:'drawback/findDrawbackListByPage',
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    salesmanList.setValue([ ]);
};